package pers.twf.twfrpc.springboot.starter.bootstrap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import pers.twf.twfRpc.RpcApplication;
import pers.twf.twfRpc.config.RegistryConfig;
import pers.twf.twfRpc.config.RpcConfig;
import pers.twf.twfRpc.model.ServiceMetaInfo;
import pers.twf.twfRpc.registry.LocalRegistry;
import pers.twf.twfRpc.registry.Registry;
import pers.twf.twfRpc.registry.RegistryFactory;
import pers.twf.twfrpc.springboot.starter.annotation.RpcService;

/**
 * 服务提供者启动类
 * 获取到所有 RpcService 注解的实现类，完成服务注册
 */
public class RpcProviderBootstrap implements BeanPostProcessor {

    /**
     * Bean 后置处理器，注册服务
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        RpcService rpcService = clazz.getAnnotation(RpcService.class);
        if (rpcService != null) {
            // 服务注册
            Class<?> interfaceClass = rpcService.interfaceClass();
            if (interfaceClass==void.class) {
                interfaceClass = clazz.getInterfaces()[0];
            }
            String serverName = interfaceClass.getName();
            String version = rpcService.version();

//            本地注册
            LocalRegistry.register(serverName,clazz);

            final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serverName);
            serviceMetaInfo.setServiceVersion(version);
            serviceMetaInfo.setServiceHost(rpcConfig.getServiceHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServicePort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serverName+"服务注册失败",e);
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
